package com.hello.controller;

import com.hello.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author Mordecai
 * @create 2017-05-08 下午7:57
 */
@Controller
public class LoginController {
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    @GetMapping("/login")
    public String loginForm(Model model) {
        model.addAttribute("user", new User(111L, "admin", "123"));
        return "login";
    }

    @GetMapping("/success")
    public String loginSuccess(/*@SessionAttribute String account, */Model model) {
        //model.addAttribute("account", account);
        model.addAttribute("user", new User(111L, "admin", "123"));
        return "result";
    }

    @ResponseBody
    @PostMapping("/login")
    public ModelMap loginSubmit(@ModelAttribute User user){//, @SessionAttribute ModelMap map) {
        users.put(user.getId(), user);
        ModelMap map = new ModelMap();
        map.addAttribute("success", true);
        map.addAttribute("user", user);
        map.addAttribute("message", "Message is OK!");
        //return "result";
        return map;
    }

    @PutMapping("/{id}")
    public String putUser(@PathVariable Long id, @ModelAttribute User user) {
        // 处理"/users/{id}"的PUT请求，用来更新User信息
        System.out.println("Update User with id = " + id);
        User u = users.get(id);
        u.setAccount(user.getAccount());
        u.setPassword(user.getPassword());
        users.put(id, u);
        return "result";
    }

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        // 处理"/users/{id}"的DELETE请求，用来删除User
        System.out.println("Delete User with id = " + id);
        users.remove(id);
        return "result";
    }
}
